<?php
/**
 * TimoPHP a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://www.TimoPHP.com/
 * Since: 2016
 */

namespace Timo\Log;


use Timo\Config\Config;
use Timo\Core\Application;
use Timo\Core\Request;

class Log
{
    /**
     * 记录日志
     *
     * @param $message
     * @param string $logFileName
     * @param string $level 日志级别 Error Debug
     * @return bool
     */
    public static function record($message, $logFileName = '', $level = '')
    {
        //当日志写入功能关闭时
        if(Config::runtime('log.record') === false){
            return true;
        }

        $logFilePath = self::getLogFilePath($logFileName, $level);
        static::makeLogFolder($logFilePath);

        //日志内容
        $message = static::buildLogContent($message);

        return error_log($message, 3, $logFilePath);
    }

    /**
     * 记录错误日志
     *
     * @param $message
     * @param string $logFileName
     */
    public static function error($message, $logFileName = '')
    {
        self::record($message, $logFileName, 'error');
    }

    /**
     * 记录调试日志
     *
     * @param $message
     * @param string $logFileName
     */
    public static function debug($message, $logFileName = '')
    {
        self::record($message, $logFileName, 'error');
    }

    /**
     * 创建日志内容
     *
     * @param $message
     * @return string
     */
    private static function buildLogContent($message)
    {
        $router = Application::controller() . '/' . Application::action();
        $client_ip = Request::getClientIP();
        if (is_array($message)) {
            $message = json_encode($message);
        }

        return sprintf('[%s %s %s] %s', date('Y-m-d H:i:s'), $client_ip, $router, $message);
    }

    /**
     * 创建日志目录
     *
     * @param $logFilePath
     */
    private static function makeLogFolder($logFilePath)
    {
        $logDir = dirname($logFilePath);
        if (!is_dir($logDir)) {
            mkdir($logDir, 0777, true);
        }
    }

    /**
     * 获取当前日志文件名
     *
     * @access private
     * @param null $logFileName 日志文件名 'sql' 'send/wx'
     * @param string $level 日志级别
     * @return string
     */
    private static function getLogFilePath($logFileName, $level = '')
    {
        $logFileName = preg_replace("@\/|\\\@", DS, $logFileName);
        //组装日志文件路径
        $path = Config::runtime('log.path') . APP_NAME . DS;
        $level = !empty($level) ? strtolower($level) . DS : '';
        if (!$logFileName) {
            $path .= date('Y-m') . DS . $level . date('d');
        } else {
            if (strpos($logFileName, DS) !== false) {
                $path .= $level . $logFileName;
            } else {
                $path .= date('Y-m') . DS . $level . $logFileName;
            }
        }
        $path .= '.log';
        return $path;
    }
}
